package com.my.demo.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.my.demo.pojo.FamilyInformation;
import com.my.demo.pojo.Identify;
import com.my.demo.pojo.PerIdentify;
import com.my.demo.service.FamilyInformationService;
import com.my.demo.service.IdentifyService;
import com.my.demo.service.PerIdentifyService;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author liangyuanshao
 * @date 2021/11/28 - 23:06
 */
@Component
public class OCR  {
  @Autowired
  JavaRunPython javaRunPython;
  @Autowired
  FamilyInformationService familyInformationService;
  @Autowired
  PerIdentifyService perIdentifyService;
  @Autowired
  IdentifyService identifyService;



  @Async
  public void run(Integer familyInformationFamilyArchiveId) {
    if (isRecognition(familyInformationFamilyArchiveId)) {
      System.out.println("家谱编号" + familyInformationFamilyArchiveId + "已被识别");
      return;
    }

    UpdateWrapper<FamilyInformation> updateWrapper1 = new UpdateWrapper<FamilyInformation>();
    updateWrapper1.eq("family_archive_id", familyInformationFamilyArchiveId).set("state", 1);
    familyInformationService.update(updateWrapper1);

    System.out.println("正在跑OCR");
    List<PerIdentify> list = getIdentities(familyInformationFamilyArchiveId);
    for (PerIdentify perIdentify : list) {
      String path = perIdentify.getImg();
      String result = null;
      try {
        result = javaRunPython.execFunc(path);
      } catch (IOException e) {
        e.printStackTrace();
      }
      Identify identify = new Identify(familyInformationFamilyArchiveId, perIdentify.getPageNumber(), 0, result, null);
      identifyService.save(identify);
      System.out.println("已添加待复核的页面：" + identify);
    }

    UpdateWrapper<FamilyInformation> updateWrapper2 = new UpdateWrapper<FamilyInformation>();
    updateWrapper2.eq("family_archive_id", familyInformationFamilyArchiveId).set("state", 2);
    familyInformationService.update(updateWrapper2);
  }

  private boolean isRecognition(Integer familyInformationFamilyArchiveId) {
    FamilyInformation familyInformation = familyInformationService.getById(familyInformationFamilyArchiveId);
    if (familyInformation.getState() == 0) {
      //未被识别
      return false;
    } else {
      return true;
    }
  }

  private List getIdentities(Integer familyInformationFamilyArchiveId) {
    QueryWrapper<PerIdentify> queryWrapper = new QueryWrapper<PerIdentify>();
    queryWrapper.orderByAsc("page_number");
    queryWrapper.eq("family_archive_id", familyInformationFamilyArchiveId);
    List<PerIdentify> list = perIdentifyService.list(queryWrapper);
    return list;
  }
}
